﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MSMQTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TransactionalQueue();
            Console.ReadKey();
        }

        private static void NonTransactionalQueue()
        {
            MessageQueue queue = new MessageQueue(@"ws-rodzwzh-01\Private$\msmqdemo", QueueAccessMode.SendAndReceive);
            Message message = new System.Messaging.Message();
            message.Body = @"\`EVENT_Id\`:218864,\`Event_Level\`:\`CRITICAL\`,\`Ticket_Id\`:\`\`,\`Event_Source\`:\`其他\`,\`Host_Id\`:\`\`,\`Begin_Time\`:\`2014-1-14 11:30:17\`,\`Event_Desc\`:\`()的端口(80)监听状态异常。\`,\`Status\`:\`CLOSED\`,\`App_Name\`:\`ESB二期\`,\`App_Code\`:\`BN_038\`,\`APP_Level\`:\`4\`";
            message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
            // Put message into queue
            queue.Send(message);
            // Set the formatter to indicate body contains an Order.
            queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            try
            {
                // Receive and format the message. 
                Message myMessage = queue.Receive();
                var mesageBody = (string)myMessage.Body;
                Console.WriteLine(mesageBody);

            }
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }
            // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static void TransactionalQueue()
        {
            //var transactionQueue = MessageQueue.Create(@"FormatName:DIRECT=TCP:10.1.115.248\private$\transactionalQueue", true);
            //transactionQueue.SetPermissions("Everyone", MessageQueueAccessRights.GenericWrite);
            //transactionQueue.SetPermissions("Everyone", MessageQueueAccessRights.GenericRead);

            MessageQueue queue = new MessageQueue(@"FormatName:DIRECT=TCP:10.1.115.248\private$\TransactionalQueue", QueueAccessMode.SendAndReceive);
            queue.MessageReadPropertyFilter.Priority = true;
            queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            TransactionlQueueReceive(queue);

        }


        private static void GetItemCountFromQueueByCategory(MessageQueue queue, string label)
        {

        }

        private static void TransactionlQueueSend(MessageQueue queue,string label)
        {
            MessageQueueTransaction myTransaction = new MessageQueueTransaction();
            
            Message message = new System.Messaging.Message();
            message.Priority = MessagePriority.VeryLow;
            message.Label = label;
            message.Body = @"msmq test message " + DateTime.Now;
            myTransaction.Begin();
            queue.Send(message, myTransaction);
            myTransaction.Commit();
            queue.Send(message);
            Console.WriteLine(label+" has been sent successfully");
        }

        private static void TransactionlQueueReceive(MessageQueue queue)
        {
            try
            {
                //读取队列消息，但不删除
                //var msgs = queue.GetAllMessages();
                //foreach (var msg in msgs)
                //{
                //    var mesageBody = (string)msg.Body+" creasteTime-"+msg.Label+" priority-"+msg.Priority;
                //    Console.WriteLine(mesageBody);
                //}

                while (true)
                {
                    //消息一旦被读取，队列里将不存在该消息
                    Message myMessage = queue.Receive(new TimeSpan(0, 0, 1));
                    var mesageBody = (string)myMessage.Body + " --  " + myMessage.Label;
                    Console.WriteLine(mesageBody);
                }
            }
            catch (MessageQueueException e)
            {
                if (e.ErrorCode == (int)MessageQueueErrorCode.IOTimeout)
                {
                    // timeout logic here
                }
                Console.WriteLine(e.Message);
            }
            // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
        }

    }
}
